package com.yubest.servletjsp.util;

import java.sql.*;
import java.util.*;

public class SqlExecutor {

    public static Map<String, Object> selectOne(String sql, Object ... args) {
        List<Map<String, Object>> list = select(sql, args);
        return list.size() > 0 ? list.get(0) : null;
    }

    public static List<Map<String, Object>> select(String sql, Object ... args) {
        List<Map<String, Object>> list = new ArrayList<>();

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        ResultSetMetaData metaData = null;
        try {
            connection = DbUtil.getConnection();
            assert connection != null;
            preparedStatement = connection.prepareStatement(sql);
            wrapStatement(preparedStatement, args);

            resultSet = preparedStatement.executeQuery();

            metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();

            while (resultSet.next()) {
                Map<String, Object> rowData = new HashMap<>();
                for (int i = 1; i <= count; i++) {
                    rowData.put(metaData.getColumnName(i), resultSet.getObject(i));
                }
                list.add(rowData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.close(connection, preparedStatement, resultSet);
        }
        return list;
    }

    public static int insert(String sql, Object ... args) {
        return update(sql, args);
    }

    public static int delete(String sql, Object ... args) {
        return update(sql, args);
    }

    public static int update(String sql, Object ... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int flag = 0;
        try {
            connection = DbUtil.getConnection();
            assert connection != null;
            preparedStatement = connection.prepareStatement(sql);
            wrapStatement(preparedStatement, args);
            connection.setAutoCommit(false);
            flag = preparedStatement.executeUpdate();
            connection.commit();
            return flag;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.close(connection, preparedStatement);
        }
        return flag;
    }

    private static void wrapStatement(PreparedStatement preparedStatement, Object ... args) throws SQLException {
        if (null != args) {
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof Integer) {
                    preparedStatement.setInt(i + 1, (Integer) args[i]);
                } else if (args[i] instanceof String) {
                    preparedStatement.setString(i + 1, (String) args[i]);
                }
            }
        }
    }

}
